<template>
  <div id="chart" class="chart"></div>
</template>

<script>
import axios from 'axios';
import * as echarts from 'echarts';

export default {
  mounted() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      axios.get('/powerPercentage/data1')
        .then(response => {
          const data = response.data.chartData1;
          const chartDataRegion = data.chartDataRegion;
          const chartDataTotal = data.chartDataTotal;

          // 计算region和total的总和
          const regionSum = chartDataRegion.reduce((sum, item) => sum + parseInt(item.num), 0);
          const totalSum = chartDataTotal.reduce((sum, item) => sum + parseInt(item.num), 0);

          // 计算用电量占比
          const chartData = [
            { name: 'Region', value: regionSum },
            { name: 'Total', value: totalSum - regionSum }
          ];

          this.initChart(chartData);
        })
        .catch(error => {
          console.error('获取数据失败', error);
        });
    },
    initChart(chartData) {
      const chartDom = document.getElementById('chart');
      const myChart = echarts.init(chartDom);
      const option = {
        title: {
          text: '用电量占比',
          left: 'center',
          textStyle: {
            fontSize: 24,
            fontWeight: 'bold',
            color: '#00FFFF'
          }

        },
        tooltip: {
          trigger: 'item',
          backgroundColor: 'rgba(0, 0, 0, 0.7)',
          borderColor: '#fff',
          borderWidth: 1,
          textStyle: {
            fontSize: 14,
            color: '#fff'
          }
        },
        legend: {
          top: '5%',
          left: 'center',
          textStyle: {
            fontSize: 14,
            color: '#00FFFF'
          }
        },
        series: [
          {
            name: '用电量占比',
            type: 'pie',
            radius: ['40%', '70%'], 
            avoidLabelOverlap: false,
            itemStyle: {
              borderColor: '#fff',
              borderWidth: 2,
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            },
            label: {
              show: true,
              position: 'inside',
              textStyle: {
                fontSize: 14,
                color: '#00FFFF'
              },
              formatter: '{d}%' // 显示百分比
            },
            labelLine: {
              show: true,
              lineStyle: {
                color: '#00FFFF'
              }
            },
            data: chartData,
            color: ['#1E90FF', '#3CB371'] 
          }
        ],
      };

      myChart.setOption(option);
    }
  }
};
</script>

<style scoped>
.chart {
  width: 70%;
  height: 600px;
  transition: all 0.3s ease-in-out;
  border-radius: 10px;
  left:  100px;
}

</style>
